package com.cy.pj.sys.service.impl;

import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Override
    public Integer updateValid(Integer id, Integer valid) {
        Subject subject = SecurityUtils.getSubject();
        SysUser user = (SysUser) subject.getPrincipal();
        System.out.println("login:" + user.getId());
        String modifiedUser = user.getUsername();
        return sysUserDao.updateValid(id, valid, modifiedUser);
    }

    @Override
    public Integer saveUser(SysUser sysUser) {
        String password = sysUser.getPassword();
        String salt = UUID.randomUUID().toString();
        SimpleHash simpleHash = new SimpleHash("MD5", password, salt, 1);
        password = simpleHash.toHex();
        sysUser.setPassword(password);
        sysUser.setSalt(salt);
        final Integer rows = sysUserDao.insertUser(sysUser);

        sysUserRoleDao.insertById(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }

    @Override
    public Integer updateUser(SysUser sysUser) {
        final Integer rows = sysUserDao.updateUser(sysUser);
        sysUserRoleDao.deleteById(sysUser.getId());
        sysUserRoleDao.insertById(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }

    @Override
    public SysUser findById(Integer id) {
        SysUser user = sysUserDao.selectById(id);
        List<Integer> roleIds = sysUserRoleDao.selectById(user.getId());
        user.setRoleIds(roleIds);
        return user;
    }

    @Override
    public List<SysUser> findUsers(SysUser sysUser) {
        return sysUserDao.selectUsers(sysUser);
    }
}
